package com.yusvn.scm.goods.bi.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import com.jfinal.aop.Inject;
import com.jfinal.ext.cors.EnableCORS;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yusvn.scm.admin.auth.AdminAuthKit;
import com.yusvn.scm.admin.auth.AdminAuthService;
import com.yusvn.scm.common.BaseController;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.SysUser;
import com.yusvn.scm.goods.bi.service.ScmBiService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;


/**
 * BI报表
 * @author liugz
 *
 */
@EnableCORS
public class ScmBiController extends BaseController {
	
	@Inject
	ScmBiService srv;

	@Inject
	AdminAuthService adminSrv;
	
	public void index() {
		renderJson();
	}

	//获取生成报表数据的时间
	public void getTableTime() {
		String bbmc = getPara(); //报表名称
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		SysUser loginUser = getLoginUser();
		kv.set("userid", loginUser.getUserId()); ////获取当前登录用户ID
		kv.set("erpUsercode", loginUser.getPhone()); //获取当前登录用户对应的ERP用户编号
		
		try {
			String ret = srv.getTableTime(bbmc, kv);
			renderJson( RetKit.ok().setData("tableTime", ret) );
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(RetKit.fail("查询异常："+e.getMessage()));
		}
	}
	
	// 获取分页数据
	public void getPages() {
		String bbmc = getPara(); //报表名称
		System.out.println(bbmc+"表名");
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		SysUser loginUser = getLoginUser();
		kv.set("userid", loginUser.getUserId()); ////获取当前登录用户ID
		kv.set("erpUsercode", loginUser.getPhone()); //获取当前登录用户对应的ERP用户编号
		
		try {
			Page<Record> recPage = srv.getPages(bbmc, kv);
			renderJson(RetKit.ok().setData( recPage.getList() ).setCount(recPage.getTotalRow()) );
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(RetKit.fail("查询异常："+e.getMessage()));
		}
	}

	//生成报表数据
	public void createTable() {
		//判断是否有报表管理权限
		//boolean hasPermission = AdminAuthKit.hasPermission(AdminAuthKit.QX_BBGLQX);

		boolean hasPermission = adminSrv.hasPermission(getLoginUserId(), AdminAuthKit.QX_BBGLQX);
		if(!hasPermission) {
			renderJson(RetKit.noAuth());
			return;
		}
		
		String bbmc = getPara(); //报表名称
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		SysUser loginUser = getLoginUser();
		kv.set("userid", loginUser.getUserId()); ////获取当前登录用户ID
		kv.set("erpUsercode", loginUser.getPhone()); //获取当前登录用户对应的ERP用户编号
		
		try {
			RetKit ret = srv.createTable(bbmc, kv);
			renderJson( ret );
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(RetKit.fail("查询异常："+e.getMessage()));
		}
	}
	
	//生成EXCEL
	public void createExcel() {
		//判断是否有报表管理权限
		boolean hasPermission = AdminAuthKit.hasPermission(AdminAuthKit.QX_BBGLQX);
		if(!hasPermission) {
			renderJson(RetKit.noAuth());
			return;
		}
		
		String bbmc = getPara(); //报表名称
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		SysUser loginUser = getLoginUser();
		kv.set("userid", loginUser.getUserId()); ////获取当前登录用户ID
		kv.set("erpUsercode", loginUser.getPhone()); //获取当前登录用户对应的ERP用户编号
		
		//将临时表中所有数据生成到EXCEL
		RetKit ret = srv.createExcel(bbmc, kv);
		
		renderJson(ret);
	}
	
	//下载所有EXCEL
	public void downloadExcel() {
		//判断是否有报表管理权限
		boolean hasPermission = AdminAuthKit.hasPermission(AdminAuthKit.QX_BBGLQX);
		if(!hasPermission) {
			renderJson(RetKit.noAuth());
			return;
		}
		
		String bbmc = getPara(); //报表名称
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		SysUser loginUser = getLoginUser();
		kv.set("userid", loginUser.getUserId()); ////获取当前登录用户ID
		kv.set("erpUsercode", loginUser.getPhone()); //获取当前登录用户对应的ERP用户编号

		String fileName = srv.getFileName(bbmc); //文件名称
		String filePath = srv.getFilePath(fileName); //文件路径
		
		try {
			FileReader fileReader = new FileReader(filePath);
			
			HttpServletResponse response = getResponse();
	        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
	        response.setCharacterEncoding("UTF-8");
	        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
	        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName,"utf-8") );
	        ServletOutputStream out = response.getOutputStream();
			
			fileReader.writeToStream(out, true);
			
			IoUtil.close(out); //关闭输出Servlet流
		} catch (Exception e) {
			e.printStackTrace();
		}
        
		renderNull();
	}
	
	//查询数据生成到excel并下载
	public void getExcel() {
		String bbmc = getPara(); //报表名称
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		String userid = getLoginUserId().toString();
		// 获取当前登录用户
		SysUser loginUser = getLoginUser();
		kv.set("userid", loginUser.getUserId()); ////获取当前登录用户ID
		kv.set("erpUsercode", loginUser.getPhone()); //获取当前登录用户对应的ERP用户编号
		
		String fileName = userid+"_"+srv.getFileName(bbmc); //文件名称 
		String filePath = srv.getFilePath(fileName); //文件路径

		//先将查询的数据生成Excel
		srv.doExcel(bbmc, kv, filePath);
		
		try {
			FileReader fileReader = new FileReader(filePath);
			
			HttpServletResponse response = getResponse();
	        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
	        response.setCharacterEncoding("UTF-8");
	        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
	        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName,"utf-8") );
	        ServletOutputStream out = response.getOutputStream();
			
			fileReader.writeToStream(out, true);
			
			IoUtil.close(out); //关闭输出Servlet流
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//删除服务器上刚生成的EXCEL文件
		try {
			FileUtil.del(filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		renderNull();
	}
	
}
